package com.emode.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
 

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
/**
 * cookie操作类
 * @author IT媛
 * @date 2014年12月25日
 */
public class CookiesUtil {
    private static String default_path ="/microbbs_3";
    private static int default_age =60*60*60*24*2;//默认保存2day时间
    // 设置age
    public static void addCookie(String name,String value,
           int age) throws UnsupportedEncodingException{
    	HttpServletResponse response =  ServletActionContext.getResponse();
        Cookie cookie = 
            new Cookie(name,URLEncoder.encode(value,"utf-8"));
        cookie.setMaxAge(age);
        cookie.setPath(default_path);
        //绑定域名设置
        //cookie.setDomain("");
        response.addCookie(cookie);
         
    }
    //默认的
    public static void addCookie(String name,String value) throws UnsupportedEncodingException{
    	//HttpServletResponse response =  ServletActionContext.getResponse();
        addCookie(name,value,default_age);
         
    }
    public static String findCookie(String name) 
           throws UnsupportedEncodingException{
    	HttpServletRequest request =  ServletActionContext.getRequest();
        String value = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(int i=0;i<cookies.length;i++){
                Cookie cookie = cookies[i];
                if(cookie.getName().equals(name)){
                    value = URLDecoder.decode(cookie.getValue(), "utf-8");
                }
            }
        }
        return value;
    }
    public static void deleteCookie(String name){
    	HttpServletResponse response =  ServletActionContext.getResponse();
        Cookie cookie = new Cookie(name,"");
        cookie.setMaxAge(0);
        cookie.setPath(default_path);
        response.addCookie(cookie);
    }
}